package cn.xspace.module.other.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.xspace.android.xafcommon.base.BaseFragment;
import com.xspace.android.xafcommon.been.BaseReturnBean;
import com.xspace.android.xafcommon.network.exception.HttpException;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.EventBusConstant;
import com.xspace.android.xafcommon.util.JSONUtil;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.Navigation;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.xspace.app.view.TitleBar;
import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.library.util.OkHttpUtils;
import cn.xspace.module.other.R;
import cn.xspace.module.other.activity.PlaceSetAct;
import cn.xspace.module.other.activity.UserInfoAct;
import cn.xspace.module.other.application.MyApplication;
import cn.xspace.module.other.bean.SettingBean;
import cn.xspace.module.other.bean.SettingBean.SettingEnum;
import cn.xspace.module.other.bean.UserInfoBeanNew;
import cn.xspace.module.other.view.adapter.SettingAdapter;
import de.greenrobot.event.EventBus;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class SettingFragment extends BaseFragment {

    private static final String TAG = SettingFragment.class.getSimpleName();

    private TitleBar mTitleBar;
    private ListView mListView;
    private SettingAdapter mAdapter;
    private RelativeLayout mAccountSetting;
    private String userId;
    private ImageView userIcon;
    private TextView userName;
    private TextView userAccountNumber;
    private TextView userLocal;
    private UserInfoBeanNew userInfoBeanNew;
    private Intent intent;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    public static SettingFragment newInstance() {
        Bundle args = new Bundle();
        SettingFragment fragment = new SettingFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View initView(LayoutInflater inflater) {
        userId = MyInfoUtil.getMyUserid(mContext);
        View view = inflater.inflate(R.layout.fragment_setting1, null);
//        requestNetData();
        mAccountSetting = (RelativeLayout) view.findViewById(R.id.setting_accountSetting);
        userIcon = (ImageView) view.findViewById(R.id.setting_iv_icon);
        userName = (TextView) view.findViewById(R.id.setting_tv_user_name);
        userAccountNumber = (TextView) view.findViewById(R.id.setting_tv_account_number);
        userLocal = (TextView) view.findViewById(R.id.setting_tv_local);
        return view;
    }

    @Override
    protected void initFindViewById(View view) {
        mTitleBar = (TitleBar) view.findViewById(R.id.setting_title_bar);
        mListView = (ListView) view.findViewById(R.id.lv_setting);
        if (!isShowBack) {
            mTitleBar.setLeftLayoutVisibility(View.GONE);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (userInfoBeanNew == null) {
            requestNetData();
        }
    }

    @Override
    public void initData() {
        mAdapter = new SettingAdapter(mContext, getSettings());
        mListView.setAdapter(mAdapter);
        requestNetData();
    }

    private void requestNetData() {
        showWaitDialog();
        LogUtil.e("SettingFragment     =======     开始请求数据 " + userId);
        final Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("user_id", userId);
        Observable.create(new Observable.OnSubscribe<Object>() {
            @Override
            public void call(Subscriber<? super Object> subscriber) {
                BaseReturnBean bean = OkHttpUtils.initHttp(Constants.QUERY_USER_INFO, requestMap);
                if (OkHttpUtils.isSuccess(bean)) {
                    UserInfoBeanNew userInfoBeanNew = JSONUtil.parseJsonToBean(bean.data, UserInfoBeanNew.class);
                    subscriber.onNext(userInfoBeanNew);
                } else {
                    subscriber.onError(new HttpException());
                }
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Object>() {

            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable throwable) {
                hideWaitDialog();
                LogUtil.e("SettingFragment     =======     请求数据失败 " + userId);
                throwable.printStackTrace();
            }

            @Override
            public void onNext(Object result) {
                hideWaitDialog();
                userInfoBeanNew = (UserInfoBeanNew) result;
                LogUtil.e("SettingFragment     =======     请求数据成功 " + userInfoBeanNew.user_name);
//                        userIcon
                loadData2view(userInfoBeanNew);

            }
        });
    }

    private void loadData2view(UserInfoBeanNew userInfoBeanNew) {
        Picasso.with(mContext).load(userInfoBeanNew.user_logo).into(userIcon);
        userName.setText(userInfoBeanNew.user_name);
        userAccountNumber.setText("账号 ： " + userInfoBeanNew.user_mobile);
        if (!"".equals(userInfoBeanNew.user_address)) {
            userLocal.setText(userInfoBeanNew.user_address);
        } else {
            userLocal.setText("未填写");
        }
    }

    @Override
    protected void initEvent() {
        mTitleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                exitActivity2();
            }
        });
        mAccountSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!MyApplication.get().isAccountConfigured()) {
                    Navigation.loginConfirm(mContext);
                    return;
                }
                intent = new Intent();
                intent.setClass(mContext, UserInfoAct.class);
//                Bundle bundle = new Bundle();
//                bundle.putParcelable("userInfoBeanNew", new UserInfoBeanNew());
//                intent.putExtras(bundle);
                mContext.startActivity(intent);
            }
        });
    }

    private List<SettingBean> getSettings() {
        List<SettingBean> list = new ArrayList<SettingBean>();
//        list.add(new SettingBean(getString(R.string.account_setting), SettingEnum.AccountSetting));
//        list.add(new SettingBean("订阅管理", SettingEnum.SubscribeManager));
//        list.add(new SettingBean("我的工作", SettingEnum.Worklog));
        list.add(new SettingBean(getString(R.string.my_favorite_activity), SettingEnum.MyFavouritePage));
        list.add(new SettingBean(getString(R.string.setting_alarm), SettingEnum.Alarm));
        list.add(new SettingBean(getString(R.string.setting_clean), SettingEnum.CleanCache));
        if ("1".equals(MyInfoUtil.getIsFarmer())) {
            list.add(new SettingBean(getString(R.string.offline_data_load), SettingEnum.OfflineData));
        }
        list.add(new SettingBean(getString(R.string.version_check), SettingEnum.CheckVersion));
        list.add(new SettingBean(getString(R.string.setting_help_doc), SettingEnum.HeloDoc));
//        list.add(new SettingBean(getString(R.string.feedback), SettingEnum.FeedBack));
        list.add(new SettingBean(getString(R.string.setting_about), SettingEnum.About));
//        list.add(new SettingBean("设备管理", SettingEnum.DeviceMgmt));
        return list;
    }


    public void onEventMainThread(Map inParam) {
        if (inParam == null)
            return;
        String type = (String) inParam.get(EventBusConstant.TYPE);
        if (UserInfoAct.TAG.equals(type)) {
            if (EventBusConstant.LONGIN_OUT.equals(inParam.get(EventBusConstant.ACTION_KEY))) {
                Log.e("settingActivity", "onEventMainThread: 接受到了关闭的讯息:" + type);
                exitActivity2();
            }
        } else if (EventBusConstant.LOGO_UPLOAD_FINISHED.equals(type)) {
            String url = inParam.get(EventBusConstant.ACTION_KEY).toString();
            Picasso.with(mContext)
                    .load(url)
                    .into(userIcon);
        } else if (PlaceSetAct.TAG.equals(type)) { //地区
            String address = (String) inParam.get("Place");
            userLocal.setText(address);
        }
    }
}
